package com.potenza.track.controller;

import java.util.*;

import javax.servlet.http.HttpServletResponse;
import javax.websocket.Session;


import com.alibaba.fastjson.JSON;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.potenza.track.domain.DriverLocation;
import com.potenza.track.service.IDriverLocationService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 车辆点Controller
 *
 * @author ruoyi
 * @date 2024-05-24
 */
@RestController
@RequestMapping("/location")
public class DriverLocationController extends BaseController
{
    @Autowired
    private IDriverLocationService driverLocationService;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 查询车辆点列表
     */
    @RequiresPermissions("track:location:list")
    @GetMapping("/list")
    public TableDataInfo list(DriverLocation driverLocation)
    {
        startPage();
        List<DriverLocation> list = driverLocationService.selectDriverLocationList(driverLocation);
        return getDataTable(list);
    }

    /**
     * 导出车辆点列表
     */
    @RequiresPermissions("track:location:export")
    @Log(title = "车辆点", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DriverLocation driverLocation)
    {
        List<DriverLocation> list = driverLocationService.selectDriverLocationList(driverLocation);
        ExcelUtil<DriverLocation> util = new ExcelUtil<DriverLocation>(DriverLocation.class);
        util.exportExcel(response, list, "车辆点数据");
    }

    /**
     * 获取车辆点详细信息
     */
    @RequiresPermissions("track:location:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(driverLocationService.selectDriverLocationById(id));
    }

    /**
     * 新增车辆点
     */
    @RequiresPermissions("track:location:add")
    @Log(title = "车辆点", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DriverLocation driverLocation)
    {
        return toAjax(driverLocationService.insertDriverLocation(driverLocation));
    }

    /**
     * 修改车辆点
     */
    @RequiresPermissions("track:location:edit")
    @Log(title = "车辆点", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DriverLocation driverLocation)
    {
        return toAjax(driverLocationService.updateDriverLocation(driverLocation));
    }

    /**
     * 删除车辆点
     */
    @RequiresPermissions("track:location:remove")
    @Log(title = "车辆点", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(driverLocationService.deleteDriverLocationByIds(ids));
    }

    @GetMapping("lists")
    public ResponseEntity<Object> list(){
//     List<DriverLocation> list = driverLocationService.list();

        List<DriverLocation> list = driverLocationService.selectDriverLocationList(null);


        StringBuilder jsonDataBuilder = new StringBuilder("{\"coordinates\": [");
        for (DriverLocation driverLocation : list) {
            jsonDataBuilder.append("{\"latitude\": ").append(driverLocation.getLatitude())
                    .append(", \"location\": ").append(driverLocation.getLocation()).append("}, ");
        }
        if (!list.isEmpty()) {
            jsonDataBuilder.deleteCharAt(jsonDataBuilder.length() - 2); // 移除最后一个逗号和空格
        }
        jsonDataBuilder.append("]}");
        String jsonData = jsonDataBuilder.toString();

        // 返回 JSON 数据
        return ResponseEntity.ok(jsonData);
    }

    /**
     * 定时器
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void scheduleTask() {
        List<DriverLocation> list = driverLocationService.selectDriverLocationList(null);

        for (int i = 0; i < 9; i++) {
        Random random = new Random();
        int randomNumber = random.nextInt(49) + 1;

        DriverLocation driverLocation = list.get(randomNumber);

        Double latitude = Double.valueOf(driverLocation.getLatitude());
        Double location = Double.valueOf(driverLocation.getLocation());
        redisTemplate.opsForGeo().add("SJJWD",new Point(location,latitude),"司机"+i);

    }
        System.out.println("定时器执行");
}


   /**
    * 获取redis中geo数据
    * */
//   @PostMapping("getGeoData")
   @Scheduled(cron = "0/6 * * * * ?")
    public AjaxResult getGeoData() {

       ArrayList<DriverLocation> list = new ArrayList<>();

       Set<String> range = redisTemplate.opsForZSet().range("SJJWD", 0, -1);
       for (Object o : range) {
           List<Point> sjjwd = redisTemplate.opsForGeo().position("SJJWD", o);
           System.out.println(sjjwd);

           for (Point point : sjjwd) {
               DriverLocation driverLocation = new DriverLocation();
               driverLocation.setLocation(String.valueOf(point.getX()));
               driverLocation.setLatitude(String.valueOf(point.getY()));
               list.add(driverLocation);
           }
       }
       Map<String, Session> userConnections = ChatWebSocketEndPoint.userConnections;
       Session admin = userConnections.get("admin");
       String s = JSON.toJSONString(list);
       admin.getAsyncRemote().sendText(s);

       System.out.println("经纬度发送成功");

       return AjaxResult.success(list);
   }

   }
